// pages/cart/cart.js

var httpUtil = require('../../utils/httpUtil.js')
var uiUtil = require('../../utils/uiUtil.js')
var util = require('../../utils/util.js')
var emptyUtil = require('../templates/empty/empty.js')
const app = getApp()
var that

Page({

  /**
   * 页面的初始数据
   */
  data: {
    identity:null,

    emptyParam: {
      emptyStatus: 0
    },
    cartList: null, //购物车列表

    selectedIdList: [], //已选择的购物车Id列表
    enableBuyCount: 0, //总的可购买数量
    saveAmount: 0.00, //节省金额
    totalAmount: 0.00, //总计金额

    startX: 0,
    startY: 0,
    dialogInputFocus:-1,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    that = this;
    this.requestCartList()
    that.setData({
      identity:app.globalData.identity
    })
  },
  onShareAppMessage: function(res) {
    return util.handleShareApp()
  },

  /**
   * 获取购物车信息
   */
  requestCartList() {
    httpUtil.PostRequest("cart_list", {}, {
      success(res) {
        var length = res.length || 0
        if (length == 0) { //内容为空
          emptyUtil.showEmptyView()
        } else {
          //设置选择状态
          var enableBuyCount = 0
          var storageSelectedList = app.cartSelectsGet() //存储的已选择商品列表
          var selectedIdList = [] //已选择的购物车ID列表
          if (storageSelectedList.length != 0) {
            for (var i = 0; i < length; i++) {
              var item = res[i]
              if (item.canBuy == '1') {
                enableBuyCount++;
              }
              var data = app.cartSelectsPkData(item.goodId, item.skuId)
              if (storageSelectedList.indexOf(data) != -1) {
                item.tIsSelected = true
                selectedIdList.push(item.cardId)
              }
            }
          }
          that.setData({
            enableBuyCount: enableBuyCount,
            cartList: res,
            selectedIdList: selectedIdList
          })
          //计算金额
          that.calcuAmount()
        }
      },
      fail(code, res) {
        var text = res || "获取购物车失败"
        emptyUtil.showFailView(text)
      },
      complete() {}
    })
  },
  /**
   * 购买数量-减少
   */
  onBugCountCutClick(e) {
    that.cartBlur();
    var index = e.currentTarget.dataset.index
    var goodItem = this.data.cartList[index]
    var lastCount = goodItem.buyCount || 1;
    if (lastCount == 1) { //原数量为0
      return;
    } else {
      uiUtil.showLoading("请稍候..")
      var count = lastCount - 1
      //更新购物车数量
      that.requestUpdateCartCount(index, goodItem.cardId, count)
    }
  },

  /**
   * 购买数量-增加
   */
  onBugCountAddClick(e) {
    that.cartBlur();
    uiUtil.showLoading("请稍候..")
    var index = e.currentTarget.dataset.index
    var goodItem = this.data.cartList[index]
    var lastCount = goodItem.buyCount || 0
    var count = lastCount + 1
    // if (count > this.data.maxBuyCount) {
    //   return;
    // } else if (count > this.data.stockCount) {
    //   return;
    // }
    //更新购物车数量
    that.requestUpdateCartCount(index, goodItem.cardId, count)
  },

  // 手动输入数量
  onConfirmDialogInputClick(e) {
    var index = e.currentTarget.dataset.index;
    if (that.data.dialogInputFocus!=index){
      this.setData({
        dialogInputFocus: index
      })
    }
  },
  cartInput(e){
    uiUtil.showLoading("请稍候..")
    var index = e.currentTarget.dataset.index
    var goodItem = this.data.cartList[index]
    var lastCount = parseInt(e.detail.value) || 1
    var count = lastCount
    //更新购物车数量
    that.requestUpdateCartCount(index, goodItem.cardId, count)
  },
  cartBlur(e){
    if (that.data.dialogInputFocus!=-1){
      that.setData({
        dialogInputFocus: -1
      })
    }
  },

  /**
   * item点击
   */
  onCardItemClick(e) {
    that.cartBlur();
    var index = e.currentTarget.dataset.index

    var cartList = this.data.cartList
    var clickItem = cartList[index]
    wx.navigateTo({
      url: '../goods/goods-detail/goods-detail?goodId=' + clickItem.goodId + '&skuId=' + clickItem.skuId
    })
  },
  
  onResultCartGoodCountAdd(goodId, skuId, count) {
    try {
      var cartList = this.data.cartList
      var length = cartList.length
      for (var i = 0; i < length; i++) {
        var item = cartList[i]
        if (item.goodId == goodId && item.skuId == skuId) {
          var lastCount = item.buyCount || 0;
          var newCount = lastCount + count
          item.buyCount = newCount

          that.setData({
            cartList: cartList
          })
          //重新计算金额
          that.calcuAmount()

          break;
        }
      }
    } catch (e) {
      console.log(e)
    }
  },

  /**
   * 购物车选择item点击
   */
  onCartItemSelectClick(e) {
    that.cartBlur();
    var index = e.currentTarget.dataset.index

    var cartList = this.data.cartList
    var clickItem = cartList[index]

    if (clickItem.canBuy != '1') {
      return;
    }

    var cartId = clickItem.cardId;

    var selectedIdList = this.data.selectedIdList;

    var selectedIdIndex = selectedIdList.indexOf(cartId)
    if (selectedIdIndex >= 0) { //已选择该商品
      selectedIdList.splice(selectedIdIndex, 1);
      clickItem.tIsSelected = false;
      app.cartSelectsDel(clickItem.goodId, clickItem.skuId)
    } else {
      selectedIdList.unshift(cartId);
      clickItem.tIsSelected = true;
      app.cartSelectsAdd(clickItem.goodId, clickItem.skuId)
    }

    this.setData({
      cartList: cartList,
      selectedIdList: selectedIdList,
    })
    this.calcuAmount()

  },

  /**
   * 删除点击
   */
  onItemDelClick(e) {
    that.cartBlur();
    wx.showModal({
      title: '删除商品',
      content: '确定要删除该商品吗?',
      showCancel: true,
      success(res) {
        if (res.confirm) {

          uiUtil.showLoading("请稍候..")
          var index = e.currentTarget.dataset.index

          var cartList = that.data.cartList
          var clickItem = cartList[index]
          var cartId = clickItem.cardId;

          httpUtil.PostRequest("update_cart_good_count", {
            cartId: cartId,
            bugCount: 0
          }, {
            success(res) {
              //删除商品列表
              cartList.splice(index, 1)
              app.cartSelectsDel(clickItem.goodId, clickItem.skuId)
              //更新已选择列表
              var selectedIdList = that.data.selectedIdList
              for (var i = 0; i < selectedIdList.length; i++) {
                var item = selectedIdList[i]
                if (item == cartId) {
                  selectedIdList.splice(i, 1)
                  break;
                }
              }

              that.setData({
                cartList: cartList,
                selectedIdList: selectedIdList
              })

              //重新计算金额
              that.calcuAmount()
              uiUtil.hideLoading()
              if (cartList.length == 0) { //内容为空
                emptyUtil.showEmptyView()
              }
            },
            fail(code, res) {
              uiUtil.showToast(res || "删除失败,请稍候重试")
            },
            complete() {}
          })
        }
      }
    })
  },

  /**
   * 全选点击
   */
  onselectAllClick() {
    var selectedIdList = []
    var cartList = this.data.cartList;
    var length = cartList.length
    var storageSelectedList = [] //需存储的已选择商品信息
    for (var i = 0; i < length; i++) {
      var item = cartList[i]
      if (item.canBuy != '1') {
        continue;
      }
      item.tIsSelected = true
      selectedIdList.unshift(item.cardId)
      storageSelectedList.push(app.cartSelectsPkData(item.goodId, item.skuId))
    }
    app.cartSelectsReset(storageSelectedList)
    this.setData({
      cartList: cartList,
      selectedIdList: selectedIdList
    })
    this.calcuAmount()
  },

  /**
   * 全不选点击
   */
  ondisSelectAllClick() {
    var cartList = this.data.cartList;
    var length = cartList.length
    for (var i = 0; i < length; i++) {
      var item = cartList[i]
      item.tIsSelected = false
    }
    app.cartSelectsReset([]) //清空所有已选择商品
    this.setData({
      cartList: cartList,
      selectedIdList: []
    })
    this.calcuAmount()
  },

  /**
   * 计算金额
   */
  calcuAmount() {
    var cartList = this.data.cartList;
    var identity = this.data.identity;
    var length = cartList.length

    var saveAmount = 0;
    var totalAmount = 0;

    for (var i = 0; i < length; i++) {
      var item = cartList[i]
      if (item.tIsSelected) {
        //（市场价-vip价格）x数量
        var everySaveAmount = item.basePrice - item.vipPrice
        if (everySaveAmount > 0) {
          saveAmount = saveAmount + (everySaveAmount * item.buyCount)
        }
        //区分合计会员价和合计市场价
        if(identity==1){
          totalAmount += (item.vipPrice * item.buyCount)
        } else {
          totalAmount += (item.basePrice * item.buyCount)
        }
      }
    }
    saveAmount = saveAmount.toFixed(2);
    totalAmount = totalAmount.toFixed(2);
    this.setData({
      saveAmount: saveAmount,
      totalAmount: totalAmount
    })
  },

  /**
   * 更新购物车数量
   */
  requestUpdateCartCount(index, cartId, count) {
    httpUtil.PostRequest("update_cart_good_count", {
      cartId: cartId,
      bugCount: count
    }, {
      success(res) {
        //更新list数值
        var cartList = that.data.cartList
        cartList[index].buyCount = count
        that.setData({
          cartList: cartList
        })
        //重新计算金额
        that.calcuAmount()

        uiUtil.hideLoading()
      },
      fail(code, res) {
        uiUtil.showToast(res || "更新数量失败")
      },
      complete() {}
    })
  },

  /**
   * 提交订单
   */
  onSubmitOrder() {
    var selectedIdList = this.data.selectedIdList
    var selectedIdLength = selectedIdList.length
    if (selectedIdLength == 0) {
      uiUtil.showToast("请选择商品..")
      return
    }
    var resultList = []
    var cartList = this.data.cartList
    var cartListLength = cartList.length
    for (var i = 0; i < cartListLength; i++) {
      var cartItem = cartList[i]
      if (cartItem.tIsSelected && cartItem.buyCount > 0) {
        resultList.push(cartItem)
      }
    }

    wx.redirectTo({
      url: '/pages/order/pre-order/pre-order?goodList=' + encodeURIComponent(JSON.stringify(resultList)),
    })

  },

  touchstart: function(e) {
    //开始触摸时 重置所有删除
    this.data.cartList.forEach(function(v, i) {

      if (v.isTouchMove) //只操作为true的

        v.isTouchMove = false;

    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      cartList: this.data.cartList

    })
  },
  touchmove: function(e) {

    var that = this,

      index = e.currentTarget.dataset.index, //当前索引

      startX = that.data.startX, //开始X坐标

      startY = that.data.startY, //开始Y坐标

      touchMoveX = e.changedTouches[0].clientX, //滑动变化坐标

      touchMoveY = e.changedTouches[0].clientY, //滑动变化坐标

      //获取滑动角度

      angle = that.angle({
        X: startX,
        Y: startY
      }, {
        X: touchMoveX,
        Y: touchMoveY
      });

    that.data.cartList.forEach(function(v, i) {

      v.isTouchMove = false

      //滑动超过30度角 return

      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX) { //右滑
          v.isTouchMove = false
        } else { //左滑
          v.isTouchMove = true
        }
      }

    })
    //更新数据
    that.cartBlur();
    that.setData({
      cartList: that.data.cartList
    })

  },
  /**

* 计算滑动角度

* @param {Object} start 起点坐标

* @param {Object} end 终点坐标

*/

  angle: function(start, end) {

    var _X = end.X - start.X,

      _Y = end.Y - start.Y

    //返回角度 /Math.atan()返回数字的反正切值

    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);

  },

})